/**
 * 
 */
package trungsi.gea.photos.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.jdo.PersistenceManager;

import org.springframework.beans.factory.annotation.Autowired;

import trungsi.gea.photos.domain.Entity;

/**
 * @author trungsi
 *
 */
public class GenericsDaoImpl<K extends Serializable, V extends Entity> implements GenericsDao<K, V> {

	private JdoTemplate template;
	private Class<V> entityClass = getGenericsEntityClass();
	
	@Autowired
	public void setJdoTemplate(JdoTemplate template) {
		this.template = template;
	}
	
	protected JdoTemplate getJdoTemplate() {
		return template;
	}
	
	@SuppressWarnings("unchecked")
	public Class<V> getGenericsEntityClass() {
		return (Class<V>) ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
	}
	
	@Override
	public void delete(final V entity) {
		template.execute(new JdoCallback<Void>() {
			@Override
			public Void doWithPersistenceManager(PersistenceManager pm) {
				System.out.println("delete " + entity);
				pm.deletePersistent(entity);
				return null;
			}});
		
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<V> findAll() {
		return template.execute(new JdoCallback<List<V>>() {
			@Override
			public List<V> doWithPersistenceManager(PersistenceManager pm) {
				return (List<V>) pm.newQuery(entityClass).execute();
			}});
	}

	@Override
	public V findById(final K key) {
		return template.execute(new JdoCallback<V>() {
			@Override
			public V doWithPersistenceManager(PersistenceManager pm) {
				return pm.getObjectById(entityClass, key);
			}});
	}

	@Override
	public void save(final V entity) {
		template.execute(new JdoCallback<Void>() {
			@Override
			public Void doWithPersistenceManager(PersistenceManager pm) {
				pm.makePersistent(entity);
				return null;
			}});
	}
}
